package com.macro.mall.portal.service.impl;

import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.MbrMemberScoreMapper;
import com.macro.mall.model.Common;
import com.macro.mall.model.MbrMemberScore;
import com.macro.mall.portal.constans.PathConstants;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.CommonService;
import com.macro.mall.portal.service.MbrMemberScoreService;
import com.macro.mall.portal.vo.OrderStatusUpdateReqVO;
import com.macro.mall.portal.vo.RespVO;
import com.macro.mall.portal.vo.TagStatistics;
import com.macro.mall.portal.vo.TrainingAvgStatistics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MbrMemberScore的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class MbrMemberScoreServiceImpl implements MbrMemberScoreService {

    private boolean isDebugEnabled = true;

    @Value("${host.mall.order}")
    private String HOST_MALL_ORDER;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CommonService commonService;
    @Autowired
    private MbrMemberScoreMapper mbrMemberScoreMapper;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化

    @Override
    public List<MbrMemberScore> find(MbrMemberScore value) {
        //TODO这里可以做通过Assist做添加查询
        List<MbrMemberScore> result = mbrMemberScoreMapper.selectMbrMemberScore(null);
        if (isDebugEnabled) {
            log.debug("执行获取MbrMemberScore数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public MbrMemberScore findOne(Long id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过MbrMemberScore的id获得MbrMemberScore对象-->失败:id不能为空");
        }
        MbrMemberScore result = mbrMemberScoreMapper.selectMbrMemberScoreById(id);
        if (isDebugEnabled) {
            log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(MbrMemberScore value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将MbrMemberScore中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        Assist assist = null;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            Long userId = memberDetails.getUmsMember().getId();
            value.setMemberId(userId);
            assist = new Assist(Assist.whereRequire("and target_type = ", value.getTargetType()),
                    Assist.whereRequire("and target_id = ", value.getTargetId()), Assist.whereRequire("and member_id = ", userId));
        } catch (Exception e) {
            log.error("",e);
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }

        int result = 0;
        try {
            mbrMemberScoreMapper.deleteMbrMemberScoreByAssist(assist);
            result = mbrMemberScoreMapper.insertNotNullMbrMemberScore(value);
            //1-课程、2-视频、3-文章、4-服务订单、5-视频订单
            if(4 == value.getTargetType() || 5==value.getTargetType()) {
                OrderStatusUpdateReqVO request = OrderStatusUpdateReqVO.builder().orderId(value.getTargetId()).preStatus("004").targetStatus("006").build();
                String url = HOST_MALL_ORDER + PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_STATUS_UPDATE;
                ResponseEntity<RespVO> responseEntity = restTemplate.postForEntity(url, request, RespVO.class);
                log.info(JSONUtil.toJsonStr(responseEntity.getBody()));
            }
        } catch (Exception e) {
            log.error("",e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将MbrMemberScore中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(MbrMemberScore value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            result = mbrMemberScoreMapper.updateNotNullMbrMemberScoreById(value);
        } catch (Exception e) {
            log.error("",e);
        }
        if (isDebugEnabled) {
            log.debug("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Long id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过MbrMemberScore的id删除MbrMemberScore-->失败:id不能为空");
            }
            Asserts.fail("执行通过MbrMemberScore的id删除MbrMemberScore-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = mbrMemberScoreMapper.deleteMbrMemberScoreById(id);
        } catch (Exception e) {
            log.error("",e);
        }
        if (isDebugEnabled) {
            log.debug("执行通过MbrMemberScore的id删除MbrMemberScore-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public MbrMemberScore findOne(Integer targetType, String targetId) {
        MbrMemberScore build = MbrMemberScore.builder().targetType(targetType).targetId(targetId).build();

        MbrMemberScore result = mbrMemberScoreMapper.selectMbrMemberScoreObjSingle(build);
        if (isDebugEnabled) {
            log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->结果:", result);
        }
        return result;
    }

    @Override
    public List<TagStatistics> scoreMax(String commonType, Integer trainingId, Integer courseId, Integer num) {
        List<TagStatistics> sumScore = new ArrayList<>();
        List<TagStatistics> result = null;
        Common common = new Common();
        common.setCommonType(commonType);
        List<Common> commons = commonService.find(common);
        commons.stream().forEach(cm->{
            Integer total = mbrMemberScoreMapper.selectScoreMax(cm.getId(),trainingId,courseId);
            if (total!=null) {
                TagStatistics tagStatistics = new TagStatistics();
                tagStatistics.setTrainingId(trainingId);
                tagStatistics.setCourseId(courseId);
                tagStatistics.setTagId(cm.getId());
                tagStatistics.setLabel(cm.getCommonDesc());
                tagStatistics.setTotal(total);
                sumScore.add(tagStatistics);
            }
        });
        if (!CollectionUtils.isEmpty(sumScore)) {
            result = sumScore.stream().sorted(Comparator.comparing(TagStatistics::getTotal, Comparator.reverseOrder())).limit(num).collect(Collectors.toList());
        }
        if (isDebugEnabled) {
            log.debug("执行获取TagStatistics数据集-->结果:{}", result);
        }
        return result;
    }

    @Override
    public TrainingAvgStatistics selectTrainingAvg(Integer trainingId) {
        TrainingAvgStatistics result = new TrainingAvgStatistics();
        Integer scoreAvg = mbrMemberScoreMapper.selectAvgScoreTrainingObjSingle(trainingId);
        result.setTrainingId(trainingId);
        result.setTrainingAvg(scoreAvg);
        if (isDebugEnabled) {
            log.debug("执行通过trainingId获得trainingId平均值-->结果:", result);
        }
        return result;
    }

}